/*
 * @Author: Mcc
 * @Date: 2024-07-09 14:34:08
 * @LastEditors: mcc 550539422@qq.com
 * @LastEditTime: 2024-07-09 15:00:34
 * @FilePath: \newsAnt\vite-project\src\axios\request.ts
 * @Description:
 *
 * Copyright (c) 2024 by Mcc, All Rights Reserved.
 */

import NProgress from 'nprogress';
import axios, { AxiosResponse } from 'axios';
import { Result } from '../assets/type/common';
NProgress.configure({ showSpinner: false });
//"http://testapi.xuexiluxian.cn"
console.log(import.meta.env.VITE_API_URL);
//1. 创建axios对象
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
});

//2. 请求拦截器
service.interceptors.request.use(
  (config) => {
    //如果接口需要token在这获取并进行判定，在接口头部添加
    let token = localStorage.getItem('token'); //此处用这个localStorage 也可以用store，因为一般登录后都会将登录信息存储到vuex中，但是如果不存储到localsStorage的话，当前页面刷新时，vuex中的内容会消失。
    if (token) {
      config.headers.authorization = token; //请求头加上token
      config.headers.token = token;
    }
    NProgress.start();
    return config;
  },
  (error) => {
    NProgress.done();
    Promise.reject(error);
  }
);

//3. 响应拦截器
service.interceptors.response.use(
  (response) => {
    NProgress.done();
    //判断code码
    return response;
  },
  (error) => {
    NProgress.done();
    return Promise.reject(error);
  }
);

export function get(url: string, params: any) {
  return new Promise((resolve, reject) => {
    service
      .get(url, { params: params })
      .then((res: AxiosResponse<Result>) => {
        resolve(res.data as unknown);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

export function post(
  url: string,
  params: any,
  config: any = { 'Content-Type': 'application/json;charset=utf-8' }
) {
  return new Promise((resolve, reject) => {
    service
      .post(url, params, config)
      .then((res: AxiosResponse<Result>) => {
        resolve(res.data as unknown);
      })
      .catch((err) => {
        reject(err);
      });
  });
}
